// src/store/taskStore.ts
import { defineStore } from 'pinia';

export interface Task {
  id: number;
  title: string;
  desc: string;
  priority: 'low' | 'medium' | 'high';
  deadline: string;
  isDone: boolean;
}

export const useTaskStore = defineStore('task', {
  state: () => ({
    tasks: [] as Task[], // 未删除的任务列表
    recycledTasks: [] as Task[], // 回收站任务
  }),
  //getter计算已完成未完成的任务
  getters: {
    // 获取所有任务
    getTasks: (state) => state.tasks,
    
    // 获取回收站任务
    getRecycledTasks: (state) => state.recycledTasks,
    
    // 统计未完成任务数量
    getPendingCount: (state) => 
      state.tasks.filter(task => !task.isDone).length,
    
    // 统计已完成任务数量
    getCompletedCount: (state) => 
      state.tasks.filter(task => task.isDone).length,
    
    // 统计任务总数
    getTotalCount: (state) => state.tasks.length,
    
    // 按优先级统计任务
    getHighPriorityCount: (state) => 
      state.tasks.filter(task => task.priority === 'high').length,
    
    getMediumPriorityCount: (state) => 
      state.tasks.filter(task => task.priority === 'medium').length,
    
    getLowPriorityCount: (state) => 
      state.tasks.filter(task => task.priority === 'low').length,
  },
  //添加任务，删除和回收
  actions: {
    // 添加新任务
    addTask(taskData: Omit<Task, 'id' | 'isDone'>) {
      const newTask: Task = {
        ...taskData,
        id: Date.now(), // 使用时间戳作为唯一ID
        isDone: false,
      };
      this.tasks.push(newTask);
    },
    
    // 切换任务完成状态
    toggleTaskStatus(id: number) {
      const task = this.tasks.find(task => task.id === id);
      if (task) {
        task.isDone = !task.isDone;
      }
    },
    
    // 删除任务到回收站
    deleteTaskToRecycle(id: number) {
      const taskIndex = this.tasks.findIndex(task => task.id === id);
      if (taskIndex !== -1) {
        const deletedTask = this.tasks.splice(taskIndex, 1)[0];
        this.recycledTasks.push(deletedTask);
      }
    },
    
    // 从回收站恢复任务
    restoreTaskFromRecycle(id: number) {
      const taskIndex = this.recycledTasks.findIndex(task => task.id === id);
      if (taskIndex !== -1) {
        const restoredTask = this.recycledTasks.splice(taskIndex, 1)[0];
        this.tasks.push(restoredTask);
      }
    },
    
    // 永久删除任务（从回收站彻底移除）
    permanentDeleteTask(id: number) {
      this.recycledTasks = this.recycledTasks.filter(task => task.id !== id);
    },
    
    // 更新任务信息
    updateTask(updatedTask: Task) {
      const taskIndex = this.tasks.findIndex(task => task.id === updatedTask.id);
      if (taskIndex !== -1) {
        this.tasks[taskIndex] = updatedTask;
      }
    },
    
    // 批量删除任务
    batchDeleteTasks(ids: number[]) {
      ids.forEach(id => this.deleteTaskToRecycle(id));
    },
    
    // 清空回收站
    clearRecycleBin() {
      this.recycledTasks = [];
    },
  },
});